package com.chaos.gateway.config.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chaos.framework.model.constant.SecurityConstants;
import com.chaos.framework.model.exception.BusinessException;
import com.nimbusds.jose.JWSObject;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


/**
 * @author Jacky
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class GatewaySecurityGlobalFilter implements GlobalFilter, Ordered {

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        //ServerHttpResponse response = exchange.getResponse();

        String accessToken = request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION_KEY);

        if (StrUtil.isBlank(accessToken) || !StrUtil.startWithIgnoreCase(accessToken, SecurityConstants.JWT_PREFIX)) {
            return chain.filter(exchange);
        }

        String token = StrUtil.replaceIgnoreCase(accessToken, SecurityConstants.JWT_PREFIX, Strings.EMPTY);
        String payload = StrUtil.toString(JWSObject.parse(token).getPayload());
        JSONObject payloadJsonObject = JSONUtil.parseObj(payload);
        checkaPyload(payloadJsonObject);

        String encoderPayload = URLEncoder.encode(payload, StandardCharsets.UTF_8);
        request = exchange.getRequest().mutate()
                .header(SecurityConstants.JWT_PAYLOAD_KEY, encoderPayload)
                .header("userId", payloadJsonObject.getStr("userId"))
                .header("adminId", payloadJsonObject.getStr("adminId"))
                .header("clientId", payloadJsonObject.getStr("client_id"))
                .header("tenantId", payloadJsonObject.getStr("tenantId"))
                .header("username", URLEncoder.encode(payloadJsonObject.getStr("username"), StandardCharsets.UTF_8))
                .build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    private void checkaPyload(JSONObject payloadJsonObject) throws BusinessException {
        //待扩展
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
